package com.zgh.usercenter.service;

import com.twetec.cms.common.util.cache.RedisCache;
import com.xxg.base.module.OperateLog;
import com.xxg.base.module.Operater;
import com.xxg.exception.BaseException;
import com.xxg.util.EncryptUtil;
import com.xxg.util.SystemConstant;
import com.xxg.util.TimeUtil;
import com.zgh.cache.CacheConstant;
import com.zgh.usercenter.module.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserCenterProxy {
    private Logger logger=LoggerFactory.getLogger(UserCenterProxy.class);

    @Autowired
    private RedisCache redisCache;

    private static final int NO_PASSWORD=23002;
    private static final String NO_PASSWORD_MESSAGE="密码为空";
    private static final int NO_PERSON=14001;
    private static final String NO_PERSON_MESSAGE="用户不存在";
    private static final int LOCK=15004;
    private static final String LOCK_MESSAGE="用户被锁定";
    private static final int PASSWORD=15001;
    private static final String PASSWORD_MESSAGE="密码错误";
    private static final int USER_STATUS_ERROR=15006;
    private static final String USER_STATUS_ERROR_MESSAGE="用户状态不正常";
    private static final int NO_PASSWORD_LABOURUNION=23004;
    private static final String NO_PASSWORD_LABOURUNION_MESSAGE="工会密码为空";
    private static final int NO_LABOURUNION=14002;
    private static final String NO_LABOURUNION_MESSAGE="工会不存在";
    private static final int PASSWORD_LABOURUNION=15002;
    private static final String PASSWORD_LABOURUNION_MESSAGE="工会密码错误";
    private static final int LOCK_LABOURUNION=15005;
    private static final String LOCK_LABOURUNION_MESSAGE="工会被锁定";
    private static final int LABOURUNION_STATUS_ERROR=15007;
    private static final String LABOURUNION_STATUS_ERROR_MESSAGE="工会状态不正常";

    private static final String LOGIN_TYPE_CHECK_PASSWORD="1";	// 登录类型
    //REDIS缓存KEY
    private static final String  REDISKEY_USER_BY_ID= CacheConstant.USER_CENTER+":userById";
    private static final String  REDISKEY_USER_BY_IDCARD= CacheConstant.USER_CENTER+":userByIdcard";
    private static final String  REDISKEY_USER_BY_MOBILE= CacheConstant.USER_CENTER+":userByMobile";
    private static final String  REDISKEY_USER_BY_EMAIL= CacheConstant.USER_CENTER+":userByEmail";


    private static final String  REDISKEY_LABOURUNION_BY_ID= CacheConstant.USER_CENTER+":labourUnionById";
    private static final String  REDISKEY_LABOURUNION_BY_NAME= CacheConstant.USER_CENTER+":labourUnionByName";
    private static final String  REDISKEY_LABOURUNION_BY_CODE= CacheConstant.USER_CENTER+":labourUnionByCode";


    private static final String  REDISKEY_OA_ORGANIZATION_BY_ID= CacheConstant.USER_CENTER+":oaOrganizationById";

    private static final String  REDISKEY_ORGANIZATION_BY_ID= CacheConstant.USER_CENTER+":organizationById";

    private static final String REDISKEY_LOCK_USER_IDS= CacheConstant.USER_CENTER+":lockUserIds";
    private static final String REDISKEY_LOCK_LABOURUNION_IDS= CacheConstant.USER_CENTER+":lockLabourUnionIds";

    private static final String REDISKEY_LOGIN_LOG= CacheConstant.USER_CENTER+":loginLog";

    public User getUser(long userId){
        User user=(User)redisCache.getMapValue(REDISKEY_USER_BY_ID, String.valueOf(userId));
        return user;
    }

    public List<User> getUser(Collection userIds) {
        return null;
    	//return (List<User>)redisCache.getMapValue(REDISKEY_USER_BY_ID, userIds);
    }

    public LabourUnion getLabourUnion(long labourUnionId){
        return (LabourUnion)redisCache.getMapValue(REDISKEY_LABOURUNION_BY_ID, String.valueOf(labourUnionId));
    }

    public Organization getOrganization(long organizationId){
        return (Organization)redisCache.getMapValue(REDISKEY_ORGANIZATION_BY_ID, String.valueOf(organizationId));
    }

    public OaOrganization getOaOrganization(long oaOrganizationId){
        return (OaOrganization)redisCache.getMapValue(REDISKEY_OA_ORGANIZATION_BY_ID, String.valueOf(oaOrganizationId));
    }


    //验证密码
    public boolean checkPwd(long userId, String password)throws BaseException{
    		User user=this.getUser(userId);
    		if(user==null){
    			return false;
    		}
            String pwd=EncryptUtil.encryptNewMD5(password,user.getCreateTime());
            if(!pwd.equals(user.getPwd())){
            	return false;
            }
            return true;
    }
    
    

    /**
     * 用户信息验证接口
     * 登录方式：可以验证密码，也可以不验证密码（通过i厦门验证）
     * 可以只输入：
     * 姓名+身份证类型+身份证号，身份证类型详见字典
     * 手机号
     * 用户名
     * osInfo：登录者操作系统信息
     * 登录来源：PC，APP,微信,手机或平板浏览器
     * */
    public User loginUser(String loginType,String idcardCode, String mobile, String email, String password,String ip,String osInfo,String source)throws BaseException{
        if(LOGIN_TYPE_CHECK_PASSWORD.equals(loginType)){
            if(StringUtils.isBlank(password)){
                throw new BaseException(NO_PASSWORD,
                        NO_PASSWORD_MESSAGE);
            }
        }

        User user=null;
        StringBuffer operateParam= new StringBuffer("{");
        operateParam.append("idcardCode:'").append(idcardCode).append("',");
        operateParam.append("mobile:'").append(mobile).append("',");
        operateParam.append("email:'").append(email).append("',");
        operateParam.append("password:'").append(password).append("',");
        operateParam.append("}");

        Operater operater=new Operater();
        operater.setIp(ip);

        if(StringUtils.isNotBlank(mobile)){
            user= getUserByMobile(mobile);
        }else if(StringUtils.isNotBlank(email)){
            user= getUserByEmail(email);
        }else if(StringUtils.isNotBlank(idcardCode)){
            user= getUserByIdcard(idcardCode);
        }else{
            OperateLog log=new OperateLog();
            log.setLogType(OperateLog.LOG_TYPE_LOGIN);
            log.setOperateModule("用户");
            log.setOperateSubModule("");
            log.setOperateData("tus_user");
            log.setOperateParam(operateParam.toString());
            log.setOperateStatus(SystemConstant.FAIL_STRING);
            log.setOperateResult(BaseException.NULL+"");
            log.setErrorMessage(BaseException.NULL_MESSAGE);
            log.setNote(osInfo);
            log.setOperaterId(operater.getUserId());
            log.setOperaterName(operater.getFullName());
            log.setOperaterIp(operater.getIp());
            log.setOperateTime(TimeUtil.getCurrentDateTime());
            log.setBusinessCode(operater.getBusinessCode());
            log.setDataCode(operater.getUserDataCode());
            redisCache.addList(REDISKEY_LOGIN_LOG, log);
            throw new BaseException(BaseException.NULL,
                    BaseException.NULL_MESSAGE);
        }

        if(user==null){
            OperateLog log=new OperateLog();
            log.setLogType(OperateLog.LOG_TYPE_LOGIN);
            log.setOperateModule("用户");
            log.setOperateSubModule("");
            log.setOperateData("tus_user");
            log.setOperateParam(operateParam.toString());
            log.setOperateStatus(SystemConstant.FAIL_STRING);
            log.setOperateResult(NO_PERSON+"");
            log.setErrorMessage(NO_PERSON_MESSAGE);
            log.setNote(osInfo);
            log.setOperaterId(operater.getUserId());
            log.setOperaterName(operater.getFullName());
            log.setOperaterIp(operater.getIp());
            log.setOperateTime(TimeUtil.getCurrentDateTime());
            log.setBusinessCode(operater.getBusinessCode());
            log.setDataCode(operater.getUserDataCode());
            redisCache.addList(REDISKEY_LOGIN_LOG, log);
            throw new BaseException(NO_PERSON,NO_PERSON_MESSAGE);
        }

        operater.setUserId(user.getId());
        operater.setFullName(user.getFullName());

        if(User.LOCK_STATUS.equals(user.getStatus())){
            OperateLog log=new OperateLog();
            log.setLogType(OperateLog.LOG_TYPE_LOGIN);
            log.setOperateModule("用户");
            log.setOperateSubModule("");
            log.setOperateData("tus_user");
            log.setOperateParam(operateParam.toString());
            log.setOperateStatus(SystemConstant.FAIL_STRING);
            log.setOperateResult(LOCK+"");
            log.setErrorMessage(LOCK_MESSAGE);
            log.setNote(osInfo);
            log.setOperaterId(operater.getUserId());
            log.setOperaterName(operater.getFullName());
            log.setOperaterIp(operater.getIp());
            log.setOperateTime(TimeUtil.getCurrentDateTime());
            log.setBusinessCode(operater.getBusinessCode());
            log.setDataCode(operater.getUserDataCode());
            redisCache.addList(REDISKEY_LOGIN_LOG, log);
            throw new BaseException(LOCK,LOCK_MESSAGE);
        }


        if(LOGIN_TYPE_CHECK_PASSWORD.equals(loginType)){
            String pwd=EncryptUtil.encryptNewMD5(password,user.getCreateTime());
            if(!pwd.equals(user.getPwd())){
                passwordError(user);
                OperateLog log=new OperateLog();
                log.setLogType(OperateLog.LOG_TYPE_LOGIN);
                log.setOperateModule("用户");
                log.setOperateSubModule("");
                log.setOperateData("tus_user");
                log.setOperateParam(operateParam.toString());
                log.setOperateStatus(SystemConstant.FAIL_STRING);
                log.setOperateResult(PASSWORD+"");
                log.setErrorMessage(PASSWORD_MESSAGE);
                log.setNote(osInfo);
                log.setOperaterId(operater.getUserId());
                log.setOperaterName(operater.getFullName());
                log.setOperaterIp(operater.getIp());
                log.setOperateTime(TimeUtil.getCurrentDateTime());
                log.setBusinessCode(operater.getBusinessCode());
                log.setDataCode(operater.getUserDataCode());
                redisCache.addList(REDISKEY_LOGIN_LOG, log);
                throw new BaseException(PASSWORD,PASSWORD_MESSAGE);
            }
        }

        if(!User.NORMAL_STATUS.equals(user.getStatus())){
            OperateLog log=new OperateLog();
            log.setLogType(OperateLog.LOG_TYPE_LOGIN);
            log.setOperateModule("用户");
            log.setOperateSubModule("");
            log.setOperateData("tus_user");
            log.setOperateParam(operateParam.toString());
            log.setOperateStatus(SystemConstant.FAIL_STRING);
            log.setOperateResult(USER_STATUS_ERROR+"");
            log.setErrorMessage(USER_STATUS_ERROR_MESSAGE);
            log.setNote(osInfo);
            log.setOperaterId(operater.getUserId());
            log.setOperaterName(operater.getFullName());
            log.setOperaterIp(operater.getIp());
            log.setOperateTime(TimeUtil.getCurrentDateTime());
            log.setBusinessCode(operater.getBusinessCode());
            log.setDataCode(operater.getUserDataCode());
            redisCache.addList(REDISKEY_LOGIN_LOG, log);
            throw new BaseException(USER_STATUS_ERROR,USER_STATUS_ERROR_MESSAGE);
        }

        //TODO 黑名单判断，黑名单是否不允许登录，还是可以登录，但有些业务不允许办理

        passwordSuccess(user);

        OperateLog log=new OperateLog();
        log.setLogType(OperateLog.LOG_TYPE_LOGIN);
        log.setOperateModule("用户");
        log.setOperateSubModule("");
        log.setOperateData("tus_user");
        log.setOperateParam(operateParam.toString());
        log.setOperateStatus(SystemConstant.SUCCESS_STRING);
        log.setOperateResult(SystemConstant.SUCCESS_STRING);
        log.setErrorMessage(null);
        log.setNote(osInfo);
        log.setOperaterId(operater.getUserId());
        log.setOperaterName(operater.getFullName());
        log.setOperaterIp(operater.getIp());
        log.setOperateTime(TimeUtil.getCurrentDateTime());
        log.setBusinessCode(operater.getBusinessCode());
        log.setDataCode(operater.getUserDataCode());
        redisCache.addList(REDISKEY_LOGIN_LOG, log);
        return user;
    }


    public User getUserByMobile(String mobile){
        User user=null;
        try{
            Long userId=(Long)redisCache.getMapValue(REDISKEY_USER_BY_MOBILE, mobile);
            if(userId!=null){
                user=(User)redisCache.getMapValue(REDISKEY_USER_BY_ID, String.valueOf(userId));
            }
        }catch(Exception ex){
            ex.printStackTrace();
            logger.error("根据手机号码从缓存获取用户错误:"+mobile);
        }
        return user;
    }

    public User getUserByEmail(String email){
        User user=null;
        try{
            Long userId=(Long)redisCache.getMapValue(REDISKEY_USER_BY_EMAIL, email);
            if(userId!=null){
                user=(User)redisCache.getMapValue(REDISKEY_USER_BY_ID, String.valueOf(userId));
            }
        }catch(Exception ex){
            logger.error("根据邮箱从缓存获取用户错误:"+email);
        }
        return user;
    }

    public User getUserByIdcard(String idcardCode){
        User user=null;
        try{
            Long userId=(Long)redisCache.getMapValue(REDISKEY_USER_BY_IDCARD, idcardCode);
            if(userId!=null){
                user=(User)redisCache.getMapValue(REDISKEY_USER_BY_ID, String.valueOf(userId));
            }
        }catch(Exception ex){
            logger.error("根据证件号从缓存获取用户错误:"+idcardCode);
        }
        return user;
    }

    private void passwordError(User user){
        try{
            user.setPasswordErrorNumber(user.getPasswordErrorNumber()+1);
            user.setLastLoginTime(TimeUtil.getCurrentDateTime());
            redisCache.addMap(REDISKEY_USER_BY_ID, String.valueOf(user.getId()),user);
            redisCache.addSet(REDISKEY_LOCK_USER_IDS, user.getId());
        }catch(Exception ex){
            logger.error("更新缓存用户信息失败:"+user.getId());
        }
    }

    private void passwordSuccess(User user){
        try{
            user.setPasswordErrorNumber(0);
            user.setLastLoginTime(TimeUtil.getCurrentDateTime());
            redisCache.addMap(REDISKEY_USER_BY_ID, String.valueOf(user.getId()),user);
        }catch(Exception ex){
            logger.error("更新用户缓存信息失败:"+user.getId());
        }
    }


    public LabourUnion loginLabourUnion(String labourUnionUnifiedCode, String labourUnionName,String password,Operater operater)throws BaseException{
        if(StringUtils.isBlank(password)){
            throw new BaseException(NO_PASSWORD_LABOURUNION,NO_PASSWORD_LABOURUNION_MESSAGE);
        }

        LabourUnion labourUnion=null;
        StringBuffer operateParam= new StringBuffer("{");
        operateParam.append("labourUnionUnifiedCode:'").append(labourUnionUnifiedCode).append("',");
        operateParam.append("labourUnionName:'").append(labourUnionName).append("',");
        operateParam.append("password:'").append(password).append("',");
        operateParam.append("}");

        if(StringUtils.isNotBlank(labourUnionUnifiedCode)){
            labourUnion=getLabourUnionByLabourUnionUnifiedCode(labourUnionUnifiedCode);
        }else if(StringUtils.isNotBlank(labourUnionName)){
            labourUnion=getLabourUnionByLabourUnionName(labourUnionName);
        }else{
            OperateLog log=new OperateLog();
            log.setLogType(OperateLog.LOG_TYPE_LOGIN_LABOURUNION);
            log.setOperateModule("工会法人");
            log.setOperateSubModule("");
            log.setOperateData("tus_labourUnion");
            log.setOperateParam(operateParam.toString());
            log.setOperateStatus(SystemConstant.FAIL_STRING);
            log.setOperateResult(BaseException.NULL+"");
            log.setErrorMessage(BaseException.NULL_MESSAGE);
            log.setNote(null);
            log.setOperaterId(operater.getUserId());
            log.setOperaterName(operater.getFullName());
            log.setOperaterIp(operater.getIp());
            log.setOperateTime(TimeUtil.getCurrentDateTime());
            log.setBusinessCode(operater.getBusinessCode());
            log.setDataCode(operater.getUserDataCode());
            redisCache.addList(REDISKEY_LOGIN_LOG, log);
            throw new BaseException(BaseException.NULL,BaseException.NULL_MESSAGE);
        }
        if(labourUnion==null){
            OperateLog log=new OperateLog();
            log.setLogType(OperateLog.LOG_TYPE_LOGIN_LABOURUNION);
            log.setOperateModule("工会法人");
            log.setOperateSubModule("");
            log.setOperateData("tus_labourUnion");
            log.setOperateParam(operateParam.toString());
            log.setOperateStatus(SystemConstant.FAIL_STRING);
            log.setOperateResult(NO_LABOURUNION+"");
            log.setErrorMessage(NO_LABOURUNION_MESSAGE);
            log.setNote(null);
            log.setOperaterId(operater.getUserId());
            log.setOperaterName(operater.getFullName());
            log.setOperaterIp(operater.getIp());
            log.setOperateTime(TimeUtil.getCurrentDateTime());
            log.setBusinessCode(operater.getBusinessCode());
            log.setDataCode(operater.getUserDataCode());
            redisCache.addList(REDISKEY_LOGIN_LOG, log);
            throw new BaseException(NO_LABOURUNION,NO_LABOURUNION_MESSAGE);
        }

        if(LabourUnion.LOCK_STATUS.equals(labourUnion.getLabourUnionStatus())){
            OperateLog log=new OperateLog();
            log.setLogType(OperateLog.LOG_TYPE_LOGIN_LABOURUNION);
            log.setOperateModule("工会法人");
            log.setOperateSubModule("");
            log.setOperateData("tus_labourUnion");
            log.setOperateParam(operateParam.toString());
            log.setOperateStatus(SystemConstant.FAIL_STRING);
            log.setOperateResult(LOCK_LABOURUNION+"");
            log.setErrorMessage(LOCK_LABOURUNION_MESSAGE);
            log.setNote(null);
            log.setOperaterId(operater.getUserId());
            log.setOperaterName(operater.getFullName());
            log.setOperaterIp(operater.getIp());
            log.setOperateTime(TimeUtil.getCurrentDateTime());
            log.setBusinessCode(operater.getBusinessCode());
            log.setDataCode(operater.getUserDataCode());
            redisCache.addList(REDISKEY_LOGIN_LOG, log);
            throw new BaseException(LOCK_LABOURUNION,LOCK_LABOURUNION_MESSAGE);
        }


        String pwd=EncryptUtil.encryptNewMD5(password,labourUnion.getCreateTime());
        if(!pwd.equals(labourUnion.getPwd())){
            passwordError(labourUnion);
            OperateLog log=new OperateLog();
            log.setLogType(OperateLog.LOG_TYPE_LOGIN_LABOURUNION);
            log.setOperateModule("工会法人");
            log.setOperateSubModule("");
            log.setOperateData("tus_labourUnion");
            log.setOperateParam(operateParam.toString());
            log.setOperateStatus(SystemConstant.FAIL_STRING);
            log.setOperateResult(PASSWORD_LABOURUNION+"");
            log.setErrorMessage(PASSWORD_LABOURUNION_MESSAGE);
            log.setNote(null);
            log.setOperaterId(operater.getUserId());
            log.setOperaterName(operater.getFullName());
            log.setOperaterIp(operater.getIp());
            log.setOperateTime(TimeUtil.getCurrentDateTime());
            log.setBusinessCode(operater.getBusinessCode());
            log.setDataCode(operater.getUserDataCode());
            redisCache.addList(REDISKEY_LOGIN_LOG, log);
            throw new BaseException(PASSWORD_LABOURUNION,PASSWORD_LABOURUNION_MESSAGE);
        }

        if(!LabourUnion.NORMAL_STATUS.equals(labourUnion.getLabourUnionStatus())){
            OperateLog log=new OperateLog();
            log.setLogType(OperateLog.LOG_TYPE_LOGIN_LABOURUNION);
            log.setOperateModule("工会法人");
            log.setOperateSubModule("");
            log.setOperateData("tus_labourUnion");
            log.setOperateParam(operateParam.toString());
            log.setOperateStatus(SystemConstant.FAIL_STRING);
            log.setOperateResult(LABOURUNION_STATUS_ERROR+"");
            log.setErrorMessage(LABOURUNION_STATUS_ERROR_MESSAGE);
            log.setNote(null);
            log.setOperaterId(operater.getUserId());
            log.setOperaterName(operater.getFullName());
            log.setOperaterIp(operater.getIp());
            log.setOperateTime(TimeUtil.getCurrentDateTime());
            log.setBusinessCode(operater.getBusinessCode());
            log.setDataCode(operater.getUserDataCode());
            redisCache.addList(REDISKEY_LOGIN_LOG, log);
            throw new BaseException(LABOURUNION_STATUS_ERROR,LABOURUNION_STATUS_ERROR_MESSAGE);
        }

        //TODO 黑名单判断

        OperateLog log=new OperateLog();
        log.setLogType(OperateLog.LOG_TYPE_LOGIN_LABOURUNION);
        log.setOperateModule("工会法人");
        log.setOperateSubModule("");
        log.setOperateData("tus_labourUnion");
        log.setOperateParam(operateParam.toString());
        log.setOperateStatus(SystemConstant.SUCCESS_STRING);
        log.setOperateResult(SystemConstant.SUCCESS_STRING);
        log.setErrorMessage(null);
        log.setNote(null);
        log.setOperaterId(operater.getUserId());
        log.setOperaterName(operater.getFullName());
        log.setOperaterIp(operater.getIp());
        log.setOperateTime(TimeUtil.getCurrentDateTime());
        log.setBusinessCode(operater.getBusinessCode());
        log.setDataCode(operater.getUserDataCode());
        redisCache.addList(REDISKEY_LOGIN_LOG, log);
        passwordSuccess(labourUnion);

        return labourUnion;
    }

    private LabourUnion getLabourUnionByLabourUnionUnifiedCode(String labourUnionUnifiedCode){
        LabourUnion labourUnion=null;
        try{
            labourUnion=(LabourUnion)redisCache.getMapValue(REDISKEY_LABOURUNION_BY_ID,
                    String.valueOf(redisCache.getMapValue(REDISKEY_LABOURUNION_BY_CODE, labourUnionUnifiedCode)));
        }catch(Exception ex){
            logger.error("根据工会社会信用代码从缓存获取工会错误:"+labourUnionUnifiedCode);
        }
        return labourUnion;
    }

    private LabourUnion getLabourUnionByLabourUnionName(String labourUnionName){
        LabourUnion labourUnion=null;
        try{
            labourUnion=(LabourUnion)redisCache.getMapValue(REDISKEY_LABOURUNION_BY_ID,
                    String.valueOf(redisCache.getMapValue(REDISKEY_LABOURUNION_BY_NAME, labourUnionName)));
        }catch(Exception ex){
            logger.error("根据工会名称从缓存获取工会错误:"+labourUnionName);
        }
        return labourUnion;
    }

    private void passwordError(LabourUnion labourUnion){
        try{
            labourUnion.setPasswordErrorNumber(labourUnion.getPasswordErrorNumber()+1);
            labourUnion.setLastLoginTime(TimeUtil.getCurrentDateTime());
            redisCache.addMap(REDISKEY_LABOURUNION_BY_ID, String.valueOf(labourUnion.getId()),labourUnion);
            redisCache.addSet(REDISKEY_LOCK_LABOURUNION_IDS, labourUnion.getId());
        }catch(Exception ex){
            logger.error("更新工会缓存信息失败:"+labourUnion.getId());
        }
    }

    private void passwordSuccess(LabourUnion labourUnion){
        try{
            labourUnion.setPasswordErrorNumber(0);
            labourUnion.setLastLoginTime(TimeUtil.getCurrentDateTime());
            redisCache.addMap(REDISKEY_LABOURUNION_BY_ID, String.valueOf(labourUnion.getId()),labourUnion);
        }catch(Exception ex){
            logger.error("更新工会缓存信息失败:"+labourUnion.getId());
        }
    }
    public void setOperater(Operater operater){
		if(operater==null || operater.getUserId()<=0){
			return;
		}
		User user=this.getUser(operater.getUserId());
		if(user==null){
    		return;
    	}
		
    	// 用户与业务组织的关系
		// 找到用户关联的全部部门，如果有关联部门则该部门的单位不存，如果仅关联单位，要保存单位，设置当前部门为主单位的主部门
		List<UserAndOrganization>  uaos = user.getUserAndOrganizations();
		if(uaos!=null && !uaos.isEmpty()){
			Set<Long> ids=new HashSet<Long>(); //暂存所有关联组织的ID
			Set<Long> bigTempIds=new HashSet<Long>(); //暂存所有关联部门的 单位的ID
			Set<Long> bigIds=new HashSet<Long>(); //暂存所有关联 单位的ID
			for(UserAndOrganization uao:uaos){
				if(uao==null){
					continue;
				}
				Organization organization=this.getOrganization(uao.getOrganizationId());
				if(organization==null || organization.getId()==null ||organization.getId()<=0){
					continue;
				}
					
				if(Organization.ORGANIZATION_TYPE_OTHER.equals(organization.getOrganizationType())){
					ids.add(organization.getId());
					bigTempIds.add(organization.getBigId());//如果组织是部门，将组织所在的单位暂时加入到bigTempIdS
				}else if(Organization.ORGANIZATION_TYPE_LABOURUNION.equals(organization.getOrganizationType())){
					//如果组织是单位，将单位ID加入到bigIdS
					bigIds.add(organization.getId());
					//找到主单位
					if(SystemConstant.YES_STRING.equals(uao.getLinkType())){
						operater.setMasterOrganizationId(organization.getId());
					}
				}
			}
			//将重复的单位删除
			bigIds.removeAll(bigTempIds);
			ids.addAll(bigIds);
			operater.setOrganizationIds(StringUtils.join(ids,","));
			//设置主部门
			for(UserAndOrganization uao:uaos){
				if(uao==null ){
					continue;
				}
				Organization organization=this.getOrganization(uao.getOrganizationId());
				if(organization==null || organization.getId()==null ||organization.getId()<=0){
					continue;
				}
				if(Organization.ORGANIZATION_TYPE_OTHER.equals(organization.getOrganizationType())){
					if(organization.getBigId()==operater.getMasterOrganizationId()){
						operater.setMasterOrganizationId(organization.getId());
						break;
					}
				}
			}
			//如果没有主部门，随便设置一个
			if(operater.getMasterOrganizationId()==0){
				operater.setMasterOrganizationId(ids.isEmpty()?0:ids.iterator().next());
			}
		}
    			
    			
		//用户与OA组织的关系
		List<UserAndOaOrganization>  uaoos=user.getUserAndOaOrganizations();
		if(uaoos!=null && !uaoos.isEmpty()){
			Set<Long> ids=new HashSet<Long>(); //暂存所有关联组织的ID
			Set<Long> bigTempIds=new HashSet<Long>(); //暂存所有关联部门的 单位的ID
			Set<Long> bigIds=new HashSet<Long>(); //暂存所有关联 单位的ID
			for(UserAndOaOrganization uaoo:uaoos){
				if(uaoo==null){
					continue;
				}
				OaOrganization oaOrganization=this.getOaOrganization(uaoo.getOrganizationId());
				if(oaOrganization==null || oaOrganization.getId()==null ||oaOrganization.getId()<=0){
					continue;
				}
					
				if(OaOrganization.ORGANIZATION_TYPE_OTHER.equals(oaOrganization.getOrganizationType())){
					ids.add(oaOrganization.getId());
					bigTempIds.add(oaOrganization.getBigId());//如果组织是部门，将组织所在的单位暂时加入到bigTempIdS
				}else if(OaOrganization.ORGANIZATION_TYPE_LABOURUNION.equals(oaOrganization.getOrganizationType())){
					//如果组织是单位，将单位ID加入到bigIdS
					bigIds.add(oaOrganization.getId());
					//找到主单位
					if(SystemConstant.YES_STRING.equals(uaoo.getLinkType())){
						operater.setMasterOaOrganizationId(oaOrganization.getId());
					}
				}
			}
			//将重复的单位删除
			bigIds.removeAll(bigTempIds);
			ids.addAll(bigIds);
			operater.setOaOrganizationIds(StringUtils.join(ids,","));
			//设置主部门
			for(UserAndOaOrganization uaoo:uaoos){
				if(uaoo==null){
					continue;
				}
				OaOrganization oaOrganization=this.getOaOrganization(uaoo.getOrganizationId());
				if(oaOrganization==null || oaOrganization.getId()==null ||oaOrganization.getId()<=0){
					continue;
				}
				if(OaOrganization.ORGANIZATION_TYPE_OTHER.equals(oaOrganization.getOrganizationType())){
					if(oaOrganization.getBigId()==operater.getMasterOaOrganizationId()){
						operater.setMasterOaOrganizationId(oaOrganization.getId());
						break;
					}
				}
			}
			//如果没有主部门，随便设置一个
			if(operater.getMasterOaOrganizationId()==0){
				operater.setMasterOaOrganizationId(ids.isEmpty()?0:ids.iterator().next());
			}
		}
	}


}
